<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\SearchDataForModel;
use app\model\ProjectTarget;
use app\model\ReviewCase;
use app\model\ReviewProject;
use app\model\Sample;
use app\model\SampleType;
use app\validate\Project as ValidateProject;
use think\exception\ValidateException;
use think\Request;

class Project extends BaseController
{
    use SearchDataForModel;


    /**
     * @User: 刘海龙
     * @Date: 2021/7/23
     * @Time: 10:16
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 查询项目
     */
    public function projectList()
    {
        $limit = $this->request->param('limit', 10);
        $data = $this->search(new ReviewProject(), [], $limit);
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/23
     * @Time: 9:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增 or 编辑
     */
    public function saveProject()
    {
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        try {
            $validator = $this->validate($data, ValidateProject::rules($id), ValidateProject::msg());
            if ($validator) {
                $data['create_id'] = $this->request->uid; //用户id
                if (intval($id) === 0) {
                    ReviewProject::create($data);
                } else {
                    $project = ReviewProject::find($id);
                    if (is_null($project)) {
                        return $this->response(403, '项目不存在');
                    }
                    $project->save($data);
                }
                return $this->response();
            }
        } catch (ValidateException $exception) {
            return $this->response(403, $exception->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/23
     * @Time: 10:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目id 读取唯一
     */
    public function projectRead($id)
    {
        $project = ReviewProject::find($id);
        if (is_null($project)) {
            return $this->response(403, '此项目不存在');
        }
        return $this->response($project->toArray());
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/7/23
     * @Time: 10:31
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除项目
     */
    public function projectDel($id)
    {
        //案件 样本点
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $project = ReviewProject::with(['samples','cases'])->find($id);
            if (is_null($project)) {
                return $this->response(404, '此项目不存在');
            }
            $project->together(['samples','cases'])->delete();
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/23
     * @Time: 16:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同步数据
     */
    public function syncProjectCase()
    {
        $data = $this->request->param();
        $review = ReviewProject::find($data['review_id']);

        if (is_null($review)) {
            return $this->response(403, '无法同步,请联系管理员');
        }
        //1.更新同步过来的testing_id和项目project_id
        $review->save(['sync_testing_id' => $data['testing_id'], 'status' => ReviewProject::SYNC_STATUS_TWO]);
//        //2.同步更新project_target表
//        $target_data = [];
//        if (count($data['city_project_target']) > 0) {
//            foreach ($data['city_project_target'] as $key => $value) {
//                $target_data[] = [
//                    'name' => $value['c_p_t_name'] ?? '暂未匹配',
//                    'sync_id' => $value['id'] ?? 0,
//                    'review_project_id' => $data['review_id']
//                ];
//            }
//        }
//        //新增到project_target
//        $project_target = new ProjectTarget();
//        $project_target->saveAll($target_data);

        //同步更新样本类别和样本及每个样本下面的案件case
        if (count($data['sample_type']) === 0) {
            return $this->response(403, '无法同步,请联系管理员');
        }

        foreach ($data['sample_type'] as $key => $v) {

            $sample_type_data = [
                'name' => $v['s_p_name'] ?? '',
                'sync_id' => $v['id'] ?? 0,
                'review_project_id' => $data['review_id'] ?? 0,
            ];
            //获取新的id
           $sample_type_id = SampleType::create($sample_type_data)->id;

            //获取样本类别下面的样本点
            if (count($v['city_project_samples']) > 0) {
                //处理样本点
                foreach ($v['city_project_samples'] as $k1 => $v1) {

                    if ($v1['s_name'] !== '无') {

                        $sample_data = [
                            'name' => $v1['s_name'] ?? '暂未匹配',
                            'sync_id' => $v1['id'] ?? 0,
                            'original_sample_type_id' => $v1['sample_type_id'] ?? 0,
                            'new_sample_type_id' => 0,
                            'review_project_id' => $data['review_id'] ?? 0,
                        ];

                        $sample_id = Sample::create($sample_data)->id;

                        if (count($v1['sim']) > 0) {
                            //处理案件
                            foreach ($v1['sim'] as $index => $item) {
                                $arr_path = json_decode($item['path'], true);
                                if (count($arr_path) > 0) {
                                    //拆分图片
                                    foreach ($arr_path as $k2 => $v2) {
                                        $case_data = [
                                            'sync_id' => $item['id'] ?? 0,
                                            'sync_path' => json_encode($v2, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?? '',
                                            'domain' => 'http://chuangcheng.ahamr.cn',
                                            'remark' => $item['remark'] ?? '',
                                            'original_project_target_id' => $item['c_p_p_id'] ?? 0,
                                            'original_sample_id' => $item['sample_id'] ?? 0,
                                            'original_sample_type_id' => $item['sample_type_id'] ?? 0,
                                            'new_sample_type_id' => $sample_type_id ?? 0,
                                            'new_sample_id' => $sample_id ?? 0,
                                            'review_project_id' => $data['review_id'] ?? 0,
                                        ];
                                        ReviewCase::create($case_data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/3
     * @Time: 9:13
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 改变项目是否在进行中
     */
    public function projectChange($id)
    {
        $project = ReviewProject::find($id);
        if (is_null($project)) {
            return $this->response(403, '项目不存在');
        }
        $is_start = $project->is_start === 0 ? 1 : 2;
        $project->save(['is_start' => $is_start]);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/8/3
     * @Time: 16:40
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取项目指标列表
     */
    public function getProjectTargetList()
    {
        $limit = $this->request->param('limit', 0);
        $res = $this->search(new ProjectTarget(), [], $limit);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/3
     * @Time: 16:36
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存项目指标
     */
    public function saveProjectTarget()
    {
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        if (intval($id) === 0) {
            ProjectTarget::create($data);
        } else {
            $project_target = ProjectTarget::find($id);
            $project_target->save($data);
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/3
     * @Time: 17:02
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除项目指标
     */
    public function delProjectTarget($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $data = ProjectTarget::find($id);
            if (is_null($data)) {
                return $this->response(404, '此项目指标不存在');
            }
            $data->delete();
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/3
     * @Time: 17:02
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * select项目指标读取
     */
    public function getProjectTargetType()
    {
        $data = ProjectTarget::select();
        return $this->response($data);
    }
}
